package cn.reyuxi.emptyview

import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

class MainPagerAdapter :
    RecyclerView.Adapter<MainePageVH>() {

    private val pageEmptySate: SparseArray<Int> by lazy {
        SparseArray(3)
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainePageVH {
        return when (viewType) {
            0 -> FramePageVH(parent)

            1 -> LinearPageVH(parent)

            2 -> ConstraintPageVH(parent)

            else -> object : MainePageVH(View(parent.context).apply {
                layoutParams = ViewGroup.LayoutParams(1, 1)
            }) {

            }
        }
    }

    override fun onBindViewHolder(
        holder: MainePageVH,
        position: Int,
        payloads: MutableList<Any>
    ) {
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads)
            return
        }

        val payload = payloads[0]
        if (payload is Int) {
            pageEmptySate.set(position, payload)
            if ((pageEmptySate[position] ?: 0) == 0) {
                holder.emptyView.hide()
            } else {
                holder.emptyView.show(pageEmptySate[position])
            }
        }
    }

    override fun onBindViewHolder(holder: MainePageVH, position: Int) {
        if ((pageEmptySate[position] ?: 0) == 0) {
            holder.emptyView.hide()
        } else {
            holder.emptyView.show(pageEmptySate[position])
        }
    }

    override fun getItemCount(): Int = 3


    fun showEmpty(page: Int, @EmptyViewTypeDef emptyType: Int) {
        if (page in 0 until itemCount) {
            notifyItemChanged(page, emptyType)
        }
    }

    fun hideEmpty(page: Int) {
        if (page in 0 until itemCount) {
            notifyItemChanged(page, 0)
        }
    }
}